package com.hdg.boot.controller;

import com.hdg.boot.bo.XirMdBo;
import com.hdg.boot.excel_listener.CreatSqlService;
import com.hdg.boot.excel_listener.UploadListener;
import com.hdg.boot.service.XirMdService;
import com.hdg.boot.util.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@RequestMapping("/md")
@RestController
public class XirMdAction {

    @Autowired
    XirMdService xirMdService;
  @Autowired
  CreatSqlService creatSqlService;

    @PostMapping("/test")
    @ResponseBody
    public RestResult test(@RequestBody XirMdBo bo) {
        return new RestResult(200, "执行成功", "-----");
    }

    @PostMapping("/addXirMd")
    @ResponseBody
    public RestResult addXirMd(List<XirMdBo> list) {
        RestResult result = new RestResult();
        xirMdService.addXirMd(list);
        return result;
    }

    /**
     * 文件上传
     * <p>1. 创建excel对应的实体对象 参照{@link XirMdBo}
     * <p>2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link UploadListener}
     * <p>3. 直接读即可
     */
    @PostMapping("upload")
    @ResponseBody
    public RestResult upload(MultipartFile file) {
        try {
            xirMdService.upload(file);
        } catch (RuntimeException e) {
            return new RestResult(500, e.getMessage(), "-----");
        } catch (Exception e) {
            return new RestResult(500, "执行失败", "-----");
        }
        return new RestResult(200, "执行成功", "-----");
    }

    /**
     * 文件上传对比数据
     * <p>1. 创建excel对应的实体对象 参照{@link XirMdBo}
     * <p>2. 由于默认一行行的读取excel，所以需要创建excel一行一行的回调监听器，参照{@link UploadListener}
     * <p>3. 直接读即可
     */
    @PostMapping("dataComparison")
    @ResponseBody
    public RestResult dataComparison(MultipartFile file) throws Exception {
        long starTime = System.currentTimeMillis();
        xirMdService.dataComparison(file);
        long endTime = System.currentTimeMillis();
        return new RestResult(200, "执行成功", "对比用时:" + (endTime - starTime) + "毫秒");
    }

    @GetMapping("download")
    public void download(HttpServletResponse response, @RequestParam String type) throws IOException {
        xirMdService.download(response, type);
    }

    @PostMapping("creatSql")
    @ResponseBody
    public RestResult creatSql() throws IOException {
        creatSqlService.creatTableSql();
        creatSqlService.creatSql();
        return new RestResult(200, "成功", "");
    }

}
